package com.shopReduce.service.impl;

import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.shopReduce.bean.ShopReduce;
import com.shopReduce.bean.UserShopReduce;
import com.shopReduce.dao.UserShopReduceMapper;
import com.shopReduce.service.IShopReduceService;
import com.shopReduce.service.IUserShopReduceService;
import com.shopUser.bean.User;
import com.shopUser.feign.UserFeign;

import shopBean.common.bean.RestResult;
import shopBean.common.responseCode.Status;
import shopBean.common.utils.DateCommonUtils;
import shopBean.common.utils.RestResultGenerator;
import shopBean.common.utils.UUIDGenerator;

import java.text.ParseException;
import java.util.Date;
@Service("userShopReduceService")
public class UserShopReduceServiceImpl implements IUserShopReduceService {
	@Autowired
	UserShopReduceMapper userShopReduceMapper;
	@Autowired
	IShopReduceService shopReduceService;
	@Autowired
	UserFeign userFeign;
	@Override
	@Transactional
	public RestResult<UserShopReduce> insert(UserShopReduce userShopReduce) throws ParseException {
		ShopReduce shopReduce = shopReduceService.get(userShopReduce.getShopReduceId());
		if(shopReduce == null) {
			return RestResultGenerator.genErrorResult("优惠券不存在", null, Status.shop_reduce_is_no_exits);
		}
		if(DateUtils.parseDate(shopReduce.getExpireDate(),"yyyy-MM-dd HH:mm:ss.SSS").getTime()<new Date().getTime()){
			return RestResultGenerator.genErrorResult("商品优惠券已过期", null, Status.shop_rdeduce_is_expire);
		}

		if(this.userShopReduceMapper.getByUserIdAndShopReduceId(userShopReduce.getShopReduceId(), userShopReduce.getUserId())!=null) {
			return RestResultGenerator.genErrorResult("已领取过，请不要重复领取",null,Status.userShopReduce_is_exits);
		}

		RestResult<User> userResult = userFeign.get(userShopReduce.getUserId());
		if(userResult == null ) {
			return RestResultGenerator.genError("系统繁忙，用户服务不可用");
		}
		if(userResult.getData() == null) {
			return RestResultGenerator.genErrorResult("用户不存在", null, Status.user_is_no_exits);
		}
		
		userShopReduce.setCreateDate(DateCommonUtils.getCurrent());
		userShopReduce.setId(UUIDGenerator.generate38());
		userShopReduceMapper.insert(userShopReduce);
		return RestResultGenerator.genSuccessResult(userShopReduce);
	}

	@Override
	@Transactional
	public int deleteByUserIdAndShopReduceId(String shopReduceId, String userId) {
		// TODO Auto-generated method stub
		return this.userShopReduceMapper.deleteByUserIdAndShopReduceId(shopReduceId, userId);
	}

	@Override
	@Transactional
	public UserShopReduce getByUserIdAndShopReduceId(String shopReduceId, String userId) {
		// TODO Auto-generated method stub
		return this.userShopReduceMapper.getByUserIdAndShopReduceId(shopReduceId, userId);
	}

}
